package site.zhanjingbo.HelloDB;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.apache.commons.dbcp2.BasicDataSource;

public class DBCPHomework {
	static final String DRIVER_NAME = "com.mysql.jdbc.Driver";
	static final String DB_URL = "jdbc:mysql://localhost:3307/cloud_study?characterEncoding=utf8";
	static final String DB_USER = "root";
	static final String DB_PASSWORD = "";

	public static BasicDataSource ds = null;

	/**
	 * 初始化数据库连接池
	 */
	public static void init() {
		ds = new BasicDataSource();
		//设置数据库基本信息
		ds.setDriverClassName(DRIVER_NAME);
		ds.setUsername(DB_USER);
		ds.setUrl(DB_URL);
		ds.setPassword(DB_PASSWORD);
	}

	/**
	 * 通过ID读取商品表，输出对应商品的名称和库存数量
	 * 
	 * @param id
	 */
	public static void findProductById(int id) {
		Connection conn = null;
		PreparedStatement ptmt = null;
		ResultSet rs = null;
		try {
			conn = ds.getConnection();
			ptmt = conn.prepareStatement("select * from Product where Id=?");

			ptmt.setInt(1, id);
			rs = ptmt.executeQuery();

			while (rs.next()) {
				System.out.println(rs.getString("ProductName") + ":" + rs.getString("Inventory"));
			}

		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			try {
				if (rs != null) {
					rs.close();
				}
				if (ptmt != null) {
					ptmt.close();
				}
				if (conn != null) {
					conn.close();
				}
			} catch (SQLException e) {
			}
		}
	}
	public static void main(String[] args) {
		init();
		findProductById(1);
	}
}
